package thread.lockpackage;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 使用Lock循环打印ABCABCABC
 */
public class PrintABCWithLock {

    private static volatile int a = 0;

    private static final int count = 30;

    private static final Lock lock = new ReentrantLock();

    static Thread printA = new Thread() {
        @Override
        public void run() {
            while (true) {
                try {
                    lock.lock();
                    if (a % 3 == 0) {
                        System.out.println("A");
                        ++a;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        }
    };
    static Thread printB = new Thread() {
        @Override
        public void run() {
            while (true) {
                try {
                    lock.lock();
                    if (a % 3 == 1) {
                        System.out.println("B");
                        ++a;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        }
    };
    static Thread printC = new Thread() {
        @Override
        public void run() {
            while (true) {
                try {
                    lock.lock();
                    if (a % 3 == 2) {
                        System.out.println("C");
                        ++a;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        }
    };

    public static void main(String[] args) {
        printA.start();
        printB.start();
        printC.start();
    }

}
